/*
 * To change this template, choose com.googlecode.jackcardgame.tools | Templates
 * and open the template in the editor.
 */

/*
 * Statistics.java
 *
 * Created on 13 Αυγ 2010, 6:42:19 πμ
 */
package com.googlecode.jackcardgame.tools;

import com.googlecode.jackcardgame.cardgame.Main;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Arrays;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.table.DefaultTableModel;

/**
 *
 * @author ssoldatos
 */
public class Statistics extends javax.swing.JDialog {

  public static int COLUMN_1 = 0;
  public static int GAMES = 1;
  public static int WINS = 2;
  public static int LOSES = 3;
  public static int DRAWS = 4;
  public static int USER_POINTS = 5;
  public static int CPU_POINTS = 6;

  /** Creates new form Statistics */
  public Statistics(java.awt.Frame parent, boolean modal) {
    super(parent, modal);
    initComponents();
    fillTotalTable();
    fillUsersTable();
    setLocationRelativeTo(parent);
    setVisible(true);
  }

  /** This method is called from within the constructor to
   * initialize the form.
   * WARNING: Do NOT modify this code. The content of this method is
   * always regenerated by the Form Editor.
   */
  @SuppressWarnings("unchecked")
  // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
  private void initComponents() {

    panel = new com.googlecode.jackcardgame.tools.JTiledPanel(Main.tsoxatile);
    tabs = new javax.swing.JTabbedPane();
    total = new com.googlecode.jackcardgame.tools.JTiledPanel(Main.tsoxatile);
    scrollpane = new javax.swing.JScrollPane();
    table_total = new javax.swing.JTable();
    players = new com.googlecode.jackcardgame.tools.JTiledPanel(Main.tsoxatile);
    scrollpane_pl = new javax.swing.JScrollPane();
    table_players = new javax.swing.JTable();
    close = new javax.swing.JLabel();

    setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
    setUndecorated(true);

    panel.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(255, 255, 255), 5));

    tabs.setBackground(new java.awt.Color(0, 153, 0));

    total.setBackground(new java.awt.Color(255, 255, 255));
    total.setOpaque(false);

    scrollpane.setBackground(new java.awt.Color(255, 255, 255));

    table_total.setAutoCreateRowSorter(true);
    table_total.setModel(new javax.swing.table.DefaultTableModel(
      new Object [][] {

      },
      new String [] {
        "Difficulty", "Games", "Wins", "Loses", "Draws", "Player Points", "CPU Points"
      }
    ) {
      Class[] types = new Class [] {
        java.lang.String.class, java.lang.Integer.class, java.lang.Integer.class, java.lang.Integer.class, java.lang.Integer.class, java.lang.Integer.class, java.lang.Integer.class
      };
      boolean[] canEdit = new boolean [] {
        false, false, false, false, false, false, false
      };

      public Class getColumnClass(int columnIndex) {
        return types [columnIndex];
      }

      public boolean isCellEditable(int rowIndex, int columnIndex) {
        return canEdit [columnIndex];
      }
    });
    table_total.setSelectionBackground(new java.awt.Color(0, 204, 102));
    scrollpane.setViewportView(table_total);

    javax.swing.GroupLayout totalLayout = new javax.swing.GroupLayout(total);
    total.setLayout(totalLayout);
    totalLayout.setHorizontalGroup(
      totalLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
      .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, totalLayout.createSequentialGroup()
        .addContainerGap()
        .addComponent(scrollpane, javax.swing.GroupLayout.DEFAULT_SIZE, 538, Short.MAX_VALUE)
        .addContainerGap())
    );
    totalLayout.setVerticalGroup(
      totalLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
      .addGroup(totalLayout.createSequentialGroup()
        .addContainerGap()
        .addComponent(scrollpane, javax.swing.GroupLayout.PREFERRED_SIZE, 190, javax.swing.GroupLayout.PREFERRED_SIZE)
        .addContainerGap(27, Short.MAX_VALUE))
    );

    tabs.addTab("Total", total);

    players.setBackground(new java.awt.Color(255, 255, 255));
    players.setOpaque(false);

    scrollpane_pl.setBackground(new java.awt.Color(255, 255, 255));

    table_players.setAutoCreateRowSorter(true);
    table_players.setModel(new javax.swing.table.DefaultTableModel(
      new Object [][] {

      },
      new String [] {
        "Player", "Games", "Wins", "Loses", "Draws", "Player Points", "CPU Points"
      }
    ) {
      Class[] types = new Class [] {
        java.lang.String.class, java.lang.Integer.class, java.lang.Integer.class, java.lang.Integer.class, java.lang.Integer.class, java.lang.Integer.class, java.lang.Integer.class
      };
      boolean[] canEdit = new boolean [] {
        false, false, false, false, false, false, false
      };

      public Class getColumnClass(int columnIndex) {
        return types [columnIndex];
      }

      public boolean isCellEditable(int rowIndex, int columnIndex) {
        return canEdit [columnIndex];
      }
    });
    table_players.setSelectionBackground(new java.awt.Color(0, 204, 102));
    scrollpane_pl.setViewportView(table_players);

    javax.swing.GroupLayout playersLayout = new javax.swing.GroupLayout(players);
    players.setLayout(playersLayout);
    playersLayout.setHorizontalGroup(
      playersLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
      .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, playersLayout.createSequentialGroup()
        .addContainerGap()
        .addComponent(scrollpane_pl, javax.swing.GroupLayout.DEFAULT_SIZE, 538, Short.MAX_VALUE)
        .addContainerGap())
    );
    playersLayout.setVerticalGroup(
      playersLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
      .addGroup(playersLayout.createSequentialGroup()
        .addContainerGap()
        .addComponent(scrollpane_pl, javax.swing.GroupLayout.PREFERRED_SIZE, 190, javax.swing.GroupLayout.PREFERRED_SIZE)
        .addContainerGap(27, Short.MAX_VALUE))
    );

    tabs.addTab("Players", players);

    close.setBackground(new java.awt.Color(255, 255, 255));
    close.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT);
    close.setIcon(new javax.swing.ImageIcon(getClass().getResource("/com/googlecode/jackcardgame/icons/close.png"))); // NOI18N
    close.setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR));
    close.addMouseListener(new java.awt.event.MouseAdapter() {
      public void mouseReleased(java.awt.event.MouseEvent evt) {
        closeMouseReleased(evt);
      }
    });

    javax.swing.GroupLayout panelLayout = new javax.swing.GroupLayout(panel);
    panel.setLayout(panelLayout);
    panelLayout.setHorizontalGroup(
      panelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
      .addGroup(panelLayout.createSequentialGroup()
        .addContainerGap()
        .addGroup(panelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
          .addGroup(panelLayout.createSequentialGroup()
            .addComponent(tabs, javax.swing.GroupLayout.DEFAULT_SIZE, 563, Short.MAX_VALUE)
            .addContainerGap())
          .addComponent(close, javax.swing.GroupLayout.Alignment.TRAILING)))
    );
    panelLayout.setVerticalGroup(
      panelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
      .addGroup(panelLayout.createSequentialGroup()
        .addComponent(close)
        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
        .addComponent(tabs, javax.swing.GroupLayout.DEFAULT_SIZE, 256, Short.MAX_VALUE)
        .addContainerGap())
    );

    javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
    getContentPane().setLayout(layout);
    layout.setHorizontalGroup(
      layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
      .addComponent(panel, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
    );
    layout.setVerticalGroup(
      layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
      .addComponent(panel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
    );

    pack();
  }// </editor-fold>//GEN-END:initComponents

    private void closeMouseReleased(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_closeMouseReleased
      dispose();
    }//GEN-LAST:event_closeMouseReleased
  // Variables declaration - do not modify//GEN-BEGIN:variables
  private javax.swing.JLabel close;
  private com.googlecode.jackcardgame.tools.JTiledPanel panel;
  private com.googlecode.jackcardgame.tools.JTiledPanel players;
  private javax.swing.JScrollPane scrollpane;
  private javax.swing.JScrollPane scrollpane_pl;
  private javax.swing.JTable table_players;
  private javax.swing.JTable table_total;
  private javax.swing.JTabbedPane tabs;
  private com.googlecode.jackcardgame.tools.JTiledPanel total;
  // End of variables declaration//GEN-END:variables

  private void fillTotalTable() {
    Object stats[][] = new Object[4][7];
    stats[Main.EASIEST][COLUMN_1] = "Easiest";
    stats[Main.EASY][COLUMN_1] = "Easy";
    stats[Main.DIFFICULT][COLUMN_1] = "Difficult";
    stats[Main.HARD][COLUMN_1] = "Hard";
    for (int i = 0; i < 4; i++) {
      for (int j = 1; j < 7; j++) {
        stats[i][j] = 0;
      }
    }
    try {
      ResultSet rs = Database.stmt.executeQuery("SELECT * FROM games");
      while (rs.next()) {
        int difficulty = rs.getInt("difficulty");
        int winner = rs.getInt("winner");
        int uPoints = rs.getInt("userPoints");
        int cPoints = rs.getInt("cpuPoints");
        stats[difficulty][GAMES] = (Integer) stats[difficulty][GAMES] + 1;
        if (winner == Database.PLAYER_WIN) {
          stats[difficulty][WINS] = (Integer) stats[difficulty][WINS] + 1;
        } else if (winner == Database.CPU_WIN) {
          stats[difficulty][LOSES] = (Integer) stats[difficulty][LOSES] + 1;
        } else {
          stats[difficulty][DRAWS] = (Integer) stats[difficulty][DRAWS] + 1;
        }
        stats[difficulty][USER_POINTS] = (Integer) stats[difficulty][USER_POINTS] + uPoints;
        stats[difficulty][CPU_POINTS] = (Integer) stats[difficulty][CPU_POINTS] + cPoints;
      }
      for (int i = 0; i < stats.length; i++) {
        Object[] is = stats[i];
        DefaultTableModel model = (DefaultTableModel) table_total.getModel();
        model.addRow(is);
      }
    } catch (SQLException ex) {
      Logger.getLogger(Statistics.class.getName()).log(Level.SEVERE, null, ex);
    }
  }

  private void fillUsersTable() {
    try {
      ResultSet rs = Database.stmt.executeQuery("SELECT * FROM users");
      int users = 0;
      while(rs.next()){
        users++;
      }
      Object stats[][] = new Object[users][7];
      for (int i = 0; i < users; i++) {
        for (int j = 0; j < 7; j++) {
          stats[i][j] = 0;
        }
      }
      rs = Database.stmt.executeQuery("select users.`name`, games.* "
          + "from users inner join games on users.user_id = games.user_id "
          + "order by users.user_id");
      String prevUser = null;
      int row = -1;
      while (rs.next()) {
        String name = rs.getString("name");
        int difficulty = rs.getInt("difficulty");
        int winner = rs.getInt("winner");
        int uPoints = rs.getInt("userPoints");
        int cPoints = rs.getInt("cpuPoints");
        if (!name.equals(prevUser)) {
          row++;
          prevUser=name;
        }
        stats[row][COLUMN_1] = name;
        stats[row][GAMES] = (Integer) stats[row][GAMES] + 1;
        if (winner == Database.PLAYER_WIN) {
          stats[row][WINS] = (Integer) stats[row][WINS] + 1;
        } else if (winner == Database.CPU_WIN) {
          stats[row][LOSES] = (Integer) stats[row][LOSES] + 1;
        } else {
          stats[row][DRAWS] = (Integer) stats[row][DRAWS] + 1;
        }
        stats[row][USER_POINTS] = (Integer) stats[row][USER_POINTS] + uPoints;
        stats[row][CPU_POINTS] = (Integer) stats[row][CPU_POINTS] + cPoints;
      }
       for (int i = 0; i < stats.length; i++) {
        Object[] is = stats[i];
        DefaultTableModel model = (DefaultTableModel) table_players.getModel();
        model.addRow(is);
      }
    } catch (SQLException ex) {
      Logger.getLogger(Statistics.class.getName()).log(Level.SEVERE, null, ex);
    }
  }
}
